import { defineStore } from "pinia";
import { reqLogin,reqUserInfo,reqLogout } from "@/api/user";
import { ref } from "vue";
import {constantRoute } from "../../router/route";
import { useRouter } from "vue-router";


const router=useRouter()
export const useUserStore=defineStore('user',()=>{
    const menuroute=constantRoute
     const userdata=ref(localStorage.getItem('user1')||'')
     const userinfo=async()=>{
      const aa= await reqUserInfo()
       console.log(aa)
      if(aa.code==200){
         userdata.value=aa.data
        
         localStorage.setItem('user1',JSON.stringify(userdata.value))
      }else{
       
         router?.push('/login')
         return Promise.reject(new Error(aa.data))
         

      }
     
      

    }
    const usertoken=ref(localStorage.getItem('token')||'')
    const userLogin=async(data:any)=>{
       const res=await reqLogin(data)
      
   
        if( res.code===200){
            usertoken.value= res.data; 
            localStorage.setItem('token', res.data)
          
           
            

        }else{
          
            return Promise.reject (new Error(res.data))
        }


    }
    const tuichu=async()=>{
       const res= await reqLogout()
       console.log(res)
        userdata.value='',
        usertoken.value='',
        localStorage.removeItem('token')
        localStorage.removeItem('user1')


    }
 
    
    return{
        tuichu,
        userLogin,
        usertoken,
        menuroute,
      userdata,
        userinfo
    }
    
    

}, 
)